﻿using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace _2._3_TcpEchoClient
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            string server = "Venus";
            int port = 7;
            TcpClient client = null;
            NetworkStream stream = null;
            byte[] byteBuffer = Encoding.ASCII.GetBytes("Hello");

            try
            {
                // Create socket that is connected to server on specified port
                client = new TcpClient(server, port);

                Console.WriteLine("Connected to server... sending echo string");
                stream = client.GetStream();

                // Send the encoded string to the server
                stream.Write(byteBuffer, 0, byteBuffer.Length);

                Console.WriteLine("Sent {0} bytes to server...", byteBuffer.Length);

                int totalBytesRcvd = 0; // Total bytes received so far
                int bytesRcvd = 0; // Bytes received in last read             
                // Receive the same string back from the server

                while (totalBytesRcvd < byteBuffer.Length)
                {
                    if ((bytesRcvd = stream.Read(byteBuffer, totalBytesRcvd,
                        byteBuffer.Length - totalBytesRcvd)) == 0)
                    {
                        Console.WriteLine("Connection closed prematurely.");
                        break;
                    }
                    totalBytesRcvd += bytesRcvd;
                }
                Console.WriteLine("Received {0} bytes from server: {1}", totalBytesRcvd, Encoding.ASCII.GetString(byteBuffer, 0, totalBytesRcvd));                
            }
            finally
            {
                stream.Close();
                client.Close();
            }
        }
    }
}